package com.kgc.crowd.distributioncrowdwebui.controller;

import com.kgc.crow.distributioncrowdcommon.api.ProjectManagerService;
import com.kgc.crow.distributioncrowdcommon.pojo.ResultEntity;
import com.kgc.crow.distributioncrowdcommon.pojo.TypePO;
import com.kgc.crow.distributioncrowdcommon.util.CrowdConstant;
import com.kgc.crow.distributioncrowdcommon.util.CrowdUtils;
import com.kgc.crow.distributioncrowdcommon.util.UploadUtil;
import com.kgc.crow.distributioncrowdcommon.vo.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/project")
public class ProjectController {
    @Value("${endpoint}")
    String endpoint;
    @Value("${accessKeyId}")
    String accessKeyId;
    @Value("${accessKeySecret}")
    String accessKeySecret;
    @Value("${folderName}")
    String folderName;
    @Value("${bucketName}")
    String bucketName;
    @Value("${domain}")
    String domain;
    @Value("${detailPictureFolderName}")
    String detailPictureFolderName;
    @Resource
    ProjectManagerService projectManagerService;

    @RequestMapping("/start.html")
    public String tstart(){
        return "start";
    }

    @RequestMapping("/start-step-1.html")
    public String startstep1(HttpSession session, Model model){
        //获取登录状态
        Object attribute = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if(attribute==null){
            return "redirect:/to/login.html";
        }
        MemberSignSuccessVO memberSignSuccessVO = (MemberSignSuccessVO)attribute;
        String to = memberSignSuccessVO.getToken();
        //加载分类信息
        ResultEntity<List<TypePO>> listResultEntity = projectManagerService.selectAllType();
        model.addAttribute(CrowdConstant.ATTR_NAME_TYPYPO_LIST,listResultEntity.getData());
        //加载标签信息
        ResultEntity<List<TagVO>> slectsAllTag = projectManagerService.slectsAllTag();
        model.addAttribute(CrowdConstant.ATTR_NAME_TAG_LIST,slectsAllTag.getData());
        //回显发起人信息
        //初始化ProjectVo
        ResultEntity<ProjectVO> projectVOResultEntity = projectManagerService.initCreation(to);
        if(projectVOResultEntity.getResult().equals(ResultEntity.FAILED)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,projectVOResultEntity.getMessage());
            return "redirect:/project/start.html";
        }
        //把ProjectVo存入Session
        session.setAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT,projectVOResultEntity.getData());
        return "start-step-1";
    }

    @RequestMapping("/upload/head/picture")
    @ResponseBody
    public ResultEntity<String> uploaHeadPicture(MultipartFile multipartFile, HttpSession session) throws IOException {
        //验证是否登录
        Object attribute = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (attribute == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        MemberSignSuccessVO memberSignSuccessVO = (MemberSignSuccessVO) attribute;
        String memer = memberSignSuccessVO.getToken();

        Object attribute1 = session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if (attribute == null) {
            return ResultEntity.failed(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        }
        ProjectVO projectVO = (ProjectVO) attribute1;
        String projectTempToken = projectVO.getProjectTempToken();

        //验证是否选择文件
        if (multipartFile == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_NO_FILE);
        }
        //获取旧文件名字
        String originalFilename = multipartFile.getOriginalFilename();
        String fileName = UploadUtil.generateFileName(originalFilename);
        //把文件对象转换问文件流
        InputStream inputStream = multipartFile.getInputStream();
        //文件上传
        UploadUtil.uploadSingleFile(endpoint, accessKeyId, accessKeySecret, fileName, folderName, bucketName, inputStream);
        //保存头图路径到redis
        String headpicturdpaht = domain + "/" + folderName + "/" + fileName;
        ResultEntity<String> stringResultEntity = projectManagerService.saveHeadPicturePath(memer, projectTempToken, headpicturdpaht);
        return stringResultEntity;
    }

    @RequestMapping("/upload/detail/picture")
    @ResponseBody
    public ResultEntity<String> uploadDetailPicture(HttpSession session,@RequestParam("detailPictureList") List<MultipartFile> detailPictureList
    ) throws IOException {
        //验证是否登录
        Object attribute = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (attribute == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        MemberSignSuccessVO memberSignSuccessVO = (MemberSignSuccessVO) attribute;
        String memer = memberSignSuccessVO.getToken();
        //验证集合是否为空
        if(CrowdUtils.collectionEffectiveCheck(detailPictureList)==false){
            return ResultEntity.failed(CrowdConstant.MESSAGE_NO_FILE);
        }

        //保存详情图片上传完的路径
        List<String> detailPicturePathList = new ArrayList<>();
        for (MultipartFile multipartFile : detailPictureList) {
            boolean empty = multipartFile.isEmpty();
            if(empty){
                continue;
            }
            //获取旧的文件名和创建新文件名
            String originalFileName = multipartFile.getOriginalFilename();
            String fileName = UploadUtil.generateFileName(originalFileName);
            InputStream inputStream = multipartFile.getInputStream();
            //文件上传
            UploadUtil.uploadSingleFile(endpoint,accessKeyId,accessKeySecret,fileName,detailPictureFolderName,bucketName,inputStream);
            String detailPiturePath = domain+"/"+detailPictureFolderName+"/"+fileName;
            detailPicturePathList.add(detailPiturePath);
        }

        Object attribute1 = session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if (attribute == null) {
            return ResultEntity.failed(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        }
        ProjectVO projectVO = (ProjectVO) attribute1;
        String projectTempToken = projectVO.getProjectTempToken();

        ResultEntity<String> stringResultEntity = projectManagerService.saveDetailPicturePathList(memer, projectTempToken, detailPicturePathList);
        return stringResultEntity;
    }

    @ResponseBody
    @RequestMapping("/save/project/information")
    public ResultEntity<String> saveProjectInfomation(ProjectVO projectVO,HttpSession session){
        //检查登录
        MemberSignSuccessVO attribute = (MemberSignSuccessVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if(attribute==null){
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        String token = attribute.getToken();
        projectVO.setMemberSignToken(token);

        //获取projectToken
        Object attribute1 = session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if(attribute1==null){
            return ResultEntity.failed(CrowdConstant.ATTR_NAME_NO_INITED_PROJECT);
        }
        ProjectVO project = (ProjectVO) attribute1;
        projectVO.setProjectTempToken(project.getProjectTempToken());

        ResultEntity<String> stringResultEntity = projectManagerService.saveProjectInformation(projectVO);
        return stringResultEntity;
    }

    @RequestMapping("/manager/to/project/return")
    public String tz(){
        return "start-step-2";
    }

    @RequestMapping("/save/return/vo")
    public String save(ReturnVO returnVO, @RequestParam("describPic") MultipartFile describPic, HttpSession session, Model model)throws IOException{
        //文件上传
        //保存ReturnVO
        // 登录检查
        Object attribute = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if(attribute == null) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_ACCESS_DENIED);
            return "login";
        }
        MemberSignSuccessVO signVO = (MemberSignSuccessVO)attribute;
        // 获取token数据
        String token = signVO.getToken();
        //獲取projectToken
        Object projectObject = session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        ProjectVO projectVO= (ProjectVO) projectObject;
        String projectTempToken = projectVO.getProjectTempToken();

        //文件上传
        // 1.判断上传的文件是否为空
        if (describPic.isEmpty()) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_NO_FILE);
            return "start-step-2";
        }
        // 2.获取文件原始文件名
        String originalFilename = describPic.getOriginalFilename();

        // 3.构造存储文件的目录名
        String folderName = describPic.getOriginalFilename();

        // 4.生成文件名
        String fileName = UploadUtil.generateFileName(originalFilename);

        // 5.获取上传文件提供的输入流
        InputStream inputStream = describPic.getInputStream();

        // 6.执行上传
        UploadUtil.uploadSingleFile(endpoint, accessKeyId, accessKeySecret, fileName, folderName, bucketName,inputStream);

        // 7.拼装上传文件后OSS平台上访问文件的路径
        String ossAccessPath = domain+"/"+folderName+"/"+fileName;

        returnVO.setMemberSignToken(token);
        returnVO.setProjectTempToken(projectTempToken);
        returnVO.setDescribPicPath(ossAccessPath);

        ResultEntity<String> resultEntity = projectManagerService.saveReturnVO(returnVO);
        if (resultEntity.getResult().equals(ResultEntity.FAILED)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,resultEntity.getMessage());
            return "start-step-2";
        }
        return "start-step-3";
    }

    @RequestMapping("/save/member/confirm/vo")
    public String saveMemberConfimInfoVO(MemberConfirmInfoVO vo, HttpSession session, Model model){
        //验证登录
        Object attribute = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if(attribute==null){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_ACCESS_DENIED);
            return "login";
        }
        MemberSignSuccessVO memberSignSuccessVO = (MemberSignSuccessVO) attribute;
        String memberSigToken = memberSignSuccessVO.getToken();

        Object attribute1 = session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if(attribute1==null){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,"请同意协议");
            return "start";
        }
        ProjectVO projectVO = (ProjectVO) attribute1;
        String projectTemToken = projectVO.getProjectTempToken();

        vo.setMemberSignToken(memberSigToken);
        vo.setProjectTempToken(projectTemToken);
        ResultEntity<String> stringResultEntity = projectManagerService.saveMemberConfirmInfoVO(vo);
        if(stringResultEntity.getResult().equals(ResultEntity.FAILED)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,stringResultEntity);
            return "start-step-3";
        }

        ResultEntity<String> stringResultEntity1 = projectManagerService.saveWholeProject(memberSigToken, projectTemToken);
        if(stringResultEntity1.getResult().equals(ResultEntity.FAILED)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,stringResultEntity);
            return "start-step-3";
        }
        return "start-step-4";
    }
}
